package com.block.mq;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.common.constant.MqConstant;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.SourceCountDTO;
import com.block.common.service.ISourceDataCountInfoService;
import com.block.common.service.LogFactory;
import org.slf4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

@Component
public class SourceCountInfoMqListener {

    private static final Logger log = LogFactory.getMqLog();

    @Autowired
    ISourceDataCountInfoService sourceDataCountInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;

    /**
     * 线索撞库统计等信息
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstant.Queue.SOURCE_COUNT_QUEUE),
            exchange = @Exchange(name = MqConstant.Exchange.LAIQIANBA_SOURCE),
            key = {MqConstant.KEY.SOURCE_COUNT_KEY}
    ))
    public void listenDirectQueue2(Message message){

        String messageBody = new String(message.getBody());
        log.info("【线索统计】【body】{}", new String(message.getBody()));
        try {

            SourceCountDTO sourceCountDTO = JSON.parseObject(messageBody, SourceCountDTO.class);

            if (ObjectUtil.isNotEmpty(sourceCountDTO.getCheckNumber())){
                // redis 缓存 存储 撞库数据
                saveCheckInfo(sourceCountDTO);

            }else {
                sourceDataCountInfoService.saveSourceCountInfo(sourceCountDTO);
            }
        }catch (Exception exception){
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("MQ_RECEIVE_EXCE", "线索统计接收异常", messageBody, exception);
        }

    }

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    private void saveCheckInfo(SourceCountDTO sourceCountDTO) {
        String dateInfo = LocalDate.now().toString();
        String redisKey = StrUtil.format(RedisKeyConstant.SOURCE_CHECK_NUMBER_CHANNEL, dateInfo,  sourceCountDTO.getChannelCode());

        stringRedisTemplate.opsForValue().increment(redisKey);
        stringRedisTemplate.expire(redisKey, 1, TimeUnit.DAYS);
    }


}
